package com.dudy.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: zhuguangDemo
 * @description:
 * @ChannelHandler.Sharable 多环境下线程安全
 * ChannelInboundHandlerAdapter：
 * 处理适配器，用来操作ChannelInboundHandlerAdapter类型的每一步骤的控制流转
 * 实现ChannelInboundHandlerAdapter，该类提供了三种方法
 * 起到的也是逻辑流程的精确控制
 * ChannelFuture返回（具体你自己有没有完成），确定下一步
 * @author: dudy
 * @create: 2018-04-12 01:02
 **/
@ChannelHandler.Sharable
public class EcoServerHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(EcoServerHandler.class);

    /**
     * 面对流的传输协议
     * channelRead()，对于每个传入的信息都要调用
     * 完整的自己信息包=20字节
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String inMsg = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
        //将消息记录到控制台channel
        logger.info("客户端" + ctx.channel().toString() + "发送的消息是：" + inMsg);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = null;
        if ("QUERY TIME ORDER".equalsIgnoreCase(inMsg)) {
            currentTime = simpleDateFormat.format(new Date(System.currentTimeMillis()));
        } else {
            currentTime = "BAD REQUEST";
        }
        //通过Unpooled这种ByteBuf管理池高效构建ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(byteBuf);
    }

    /**
     * 通知ChannelInboundHandler最后一次channelRead
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
//        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("主机:"+ctx.channel().remoteAddress()+"出现异常" + cause);
        ctx.close();
//        super.exceptionCaught(ctx, cause);
    }
}

